<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/homeIndex' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>膳食计划</el-breadcrumb-item>
    </el-breadcrumb>

    <div style="margin-top: 20px; margin-bottom: 20px;">
      <el-col :span="24">
        <!-- 放搜索条件 
        :inline="ture"让表单元素占一行,一行不够会换行-->
        <el-form :inline="true">
          <el-form-item label="老人姓名">
            <el-input v-model="orderParam.olderName" placeholder="老人姓名"></el-input>
          </el-form-item>
          <el-form-item label="订餐状态">
            <el-select placeholder="订餐状态" v-model="orderParam.status">
              <el-option
                v-for="status in statusType"
                :key="status.id"
                :label="status.name"
                :value="status.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="clear">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadFoodPackageLinkList">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <el-card style="float: left ;width: 1000px;height: 100%;margin: 10px">
      <el-divider content-position="left">老人详情表格</el-divider>
      <el-button icon="el-icon-edit" type="warning" @click="addOlder()">新增订餐</el-button>

      <!--  老人订餐表格  -->

      <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        style="width: 100%"
        border
        :data="olderFoodPackageLinkArr"
      >
        <el-table-column type="selection" width="45"></el-table-column>
        <el-table-column type="index" label="编号" width="70"></el-table-column>
        <el-table-column prop="userNum" label="老人编号"></el-table-column>
        <el-table-column prop="olderName" width="85" label="老人姓名"></el-table-column>
        <el-table-column label="套餐名称" width="120" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.foodPackageName==null">(该老人还没有绑定套餐)</p>
            <el-button
              type="danger"
              round
              v-if="scope.row.foodPackageName!=null"
              @click="openFoodPackageInfo(scope.row.foodPackageId)"
            >{{scope.row.foodPackageName}}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="autoRenew" label="续期状态" width="80">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.autoRenew === 0 ? 'success' : scope.row.autoRenew === 1 ? 'danger' : 'info'"
            >{{ scope.row.autoRenew === 0 ? '未续' : scope.row.autoRenew === 1 ? '已续' : '其他' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订餐状态" width="80">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 0 ? 'success' : scope.row.status === 1 ? 'danger' : 'info'"
            >{{ scope.row.status === 0 ? '过期' : scope.row.status === 1 ? '订餐中' : '其他' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="gmtCreate"
          label="订餐时间"
          :formatter="row => formatDate(row.gmtCreate)"
        ></el-table-column>
        <el-table-column
          prop="gmtModified"
          label="结束时间"
          :formatter="row => formatDate(row.gmtModified)"
        ></el-table-column>

        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <el-button type="primary">
                操作
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="warning"
                    v-if="scope.row.foodPackageName!=null"
                    @click="updateOlder(scope.row.id)"
                  >编辑</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="info"
                    icon="el-icon-delete"
                    v-if="scope.row.foodPackageName!=null"
                    @click="openDeleteConfirm(scope.row.id)"
                  >删除</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button size="mini" type="primary" @click="selectUserall(scope.row)">查看详情</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style>
        <el-pagination
          background
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          :current-page="pageNum"
          layout="total, sizes, prev, pager, next"
          @next-click="nextPage"
          @prev-click="prevPage"
          @size-change="sizeChange"
          @current-change="currentPage"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- //右边详细信息 -->
    <el-card style="float: right ;width: 700px;height: 100%;margin: 10px">
      <el-divider content-position="left">详细信息</el-divider>
      <el-form>
        <div class="card-wrapper" style="position: relative; margin-top: 20px;">
          <span
            style="position: absolute; top: -35px; background: rgb(255, 255, 255); padding: 0 50px;"
          >老人信息</span>
          <el-card class="box-card custom-card">
            <el-row>
              <el-col :span="12">
                <el-form-item label="老人姓名" label-width="100px">
                  <el-input v-model="user.name" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="老人档案" label-width="100px">
                  <el-input v-model="user.userNum" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="入院时间" label-width="100px">
                  <el-input v-model="user.inTime" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入院区域" label-width="100px">
                  <el-input v-model="user.areaName" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="床位号" label-width="100px">
                  <el-input v-model="user.number" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入院房间" label-width="100px">
                  <el-input v-model="user.roomnum" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="性别" label-width="100px">
                  <el-input :value="genderStr" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="老人年龄" label-width="100px">
                  <el-input v-model="user.age" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="所选套餐" label-width="100px">
                  <el-input v-model=" olderFoodById.foodPackageName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="套餐价格" label-width="100px">
                  <el-input v-model="olderFoodById.totalprice" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-form>
    </el-card>
    <!--    弹出的套餐信息表-->

    <el-dialog title="套餐信息" :visible.sync="foodPackageInfoVisible">
      <el-row :gutter="15" style="text-align: center">
        <el-col :span="8" v-for="(item, index) in foodPackageInfo" :key="index">
          <div style="width: 230px; text-align: center; margin-bottom: 30px">
            <img
              :src="item.foodUrl"
              style="border-radius: 50%;margin: 0 auto;border-color: #E6A23C;border-style: solid;border-width: 3px"
              width="100"
              height="100"
            />
            <p style="font-size: 15px;font-weight: bold;color: #E6A23C">{{item.foodName}}</p>
            <p style="font-size: 15px;font-weight: bold;color: #bdbcb1">价格(元):{{item.foodPrice}}</p>
            <p style="font-size: 15px;font-weight: bold;color: #E6A23C">{{item.meal}}</p>
          </div>
        </el-col>
      </el-row>
    </el-dialog>

    <!--    弹出的修改关联的表单-->

    <el-dialog title="修改老人餐品关联" :visible.sync="editdialogVisible">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="80px">
        <el-form-item label="老人选择" prop="olderId" :label-width="formLabelWidth">
          <el-select placeholder="请选择" v-model="editForm.olderId">
            <el-option v-for="c in olderArr" :key="c.id" :label="c.name" :value="c.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="套餐选择" prop="foodPackageId" :label-width="formLabelWidth">
          <el-select placeholder="请选择" v-model="editForm.foodPackageId">
            <el-option v-for="c in foodPackageArr" :key="c.id" :label="c.name" :value="c.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="success" @click="updateForm('editForm')">修改关联</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      pageNum: 1,
      pageSize: 5,
      total: 0,
      editForm: { id: "", olderId: "", foodPackageId: "" },
      editdialogVisible: false,
      statusType: [
        { id: "1", name: "订餐中" },
        { id: "0", name: "过期" }
      ],
      autoRenewType: [
        { id: "1", name: "自动续期" },
        { id: "0", name: "未自动续" }
      ],
      user: {},
      filteredData: {},
      foodPackageArr: [],
      olderFoodPackageLinkArr: [],
      foodPackageInfoVisible: false,
      foodPackageInfo: [],
      formLabelWidth: "120px",
  
      addNewForm: { olderId: "", foodPackageId: "" },
      olderArr: [],
      orderParam: {
        olderName: "",
        status: ""
      },
      rules: {
        foodPackageId: [
          { required: true, message: "请输入套餐名称", trigger: "blur" }
        ],
        olderId: [{ required: true, message: "请输入老人", trigger: "blur" }]
      },
      olderFoodById: {},
      selectData: []
    };
  },
  methods: {
    clear() {
      this.orderParam.olderName = "";
      this.orderParam.status = "";
    },
    //分页1
    prevPage(val) {
      //点击上一页触发
      this.pageNum = val;
      this.loadFoodPackageLinkList();
    },
    nextPage(val) {
      //点击下一页触发
      this.pageNum = val;
      this.loadFoodPackageLinkList();
    },
    sizeChange(val) {
      //val每一页条数
      this.pageNum = 1;
      this.pageSize = val;
      this.loadFoodPackageLinkList();
    },
    currentPage(val) {
      this.pageNum = val;
      this.loadFoodPackageLinkList();
    },
    queryCondition() {
      this.pageNum = 1;
      this.loadFoodPackageLinkList();
    },
    addOlder() {
      this.$router.push({ path: "/addOlderFood" });
    },
    updateOlder(val){
      this.$router.push({ path: "/updateOlderFood", query: { id: val } });

    },
    openDeleteConfirm(id) {
    
      let message =
        '此操作将老人订餐删除，是否继续？';
      this.$confirm(message, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.handleDelete(id);
        })
        .catch(() => {});
    },
    //删除 this.loadFoodPackageLinkList();
    handleDelete(val) {
      console.log(val); // 在这里打印val
      this.$confirm("真的确认删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$axios
          .get("api/olderFood/deleteOlderFood/" + val)
          .then(res => {
            if (res.data.code == 200) {
              //发删除请求
              this.$message.success("删除成功!");
              this.loadFoodPackageLinkList();
            }
          });
      });
    },
    openEditDialog(OlderfoodPackage) {
      this.editdialogVisible = true;
      let url =
        "http://localhost:8080/food-packages/link/" + OlderfoodPackage.id;
      console.log("url = " + url);
      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt")
          }
        })
        .get(url)
        .then(response => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.editForm = responseBody.data;
            console.log("修改的对象:{}", this.editForm);
          } else {
            this.$alert(responseBody.message, "警告", {
              confirmButtonText: "确定",
              callback: action => {
                this.loadFoodPackageLinkList();
              }
            });
          }
        });
    },
    //列表展示所有，olderFoodPackageLinkArr
    loadFoodPackageLinkList() {
      //带分页参数pageNum,pageSize
      let pageParam = {};
      pageParam.pageNum = this.pageNum;
      pageParam.pageSize = this.pageSize;
      pageParam.param = this.orderParam;

      this.$axios.post("api/olderFood/queryOlderFood", pageParam).then(res => {
        if (res.data.code == 200) {
          let pageData = res.data.data;

          this.olderFoodPackageLinkArr = pageData.list;
          console.log("1" + this.olderFoodPackageLinkArr);
          //给分页参数赋值
          this.total = pageData.total;
          this.pageNum = pageData.pageNum;
          this.pageSize = pageData.pageSize;
        }
      });
    },

    loadFoodPackageList() {
      let url = "http://localhost:8080/food-packages/list";
      console.log("url = " + url);
      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt")
          }
        })
        .get(url)
        .then(response => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.foodPackageArr = responseBody.data;
          }
          console.log("套餐数组:{}", this.foodPackageArr);
        });
    },
    openFoodPackageInfo(val) {
      this.foodPackageInfoVisible = true;

      this.$axios.get("api/foodPackage/queryByPackageId/" + val).then(res => {
        if (res.data.code == 200) {
          const originalForm = res.data.data;
          this.foodPackageInfo = originalForm;
          console.log("查询的对象:{}", this.foodPackageInfo);
        }
      });
    },
    updateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let url = "http://localhost:8080/food-packages/link/update";
          console.log("url = " + url);
          let formData = this.qs.stringify(this.editForm);
          console.log("formData = " + formData);

          this.axios
            .create({
              headers: {
                Authorization: localStorage.getItem("jwt")
              }
            })
            .post(url, formData)
            .then(response => {
              let responseBody = response.data;
              if (responseBody.state == 20000) {
                this.loadFoodPackageLinkList();
                this.editdialogVisible = false;
                this.$message({ message: "修改关联成功！", type: "success" });
              } else {
                this.$message.error(responseBody.message);
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  
    queryInCare(val) {
      this.$axios.get("api/olderFood/queryByIdOlder/" + val).then(res => {
        if (res.data.code == 200) {
          this.user = res.data.data;
        }
      });
    },
    queryByid(id) {
      this.$axios.get("api/olderFood/queryById/" + id).then(res => {
        if (res.data.code == 200) {
          this.olderFoodById = res.data.data; // 使用this来引用data()中的originalForm
        }
      });
    },
    //调用2个方法
    selectUserall(row) {
      this.queryInCare(row.userNum);
      this.queryByid(row.id);
    },

    formatDate(date) {
      if (!date) return null;

      return new Date(date).toISOString().substr(0, 10); // 日期格式化为 YYYY-MM-DD
    }
  },
  mounted() {
    this.loadFoodPackageLinkList();
  },
  computed: {
    genderStr: function() {
      return this.user.gender === 1 ? "男" : "女";
    }
  }
};
</script>

<style scoped>
</style>